/*---------------------------
|+++++++++++++++++++++++++++|			
|	   Nguyen Duc Tai		|
|++++++++_THREAD_H_+++++++++|
---------------------------*/
#include "Thread.h"
#include <iostream>

using namespace std;

//create the thread
void Thread::start()
{	
	pthread_attr_init( &this->attribute );    
	int result = pthread_create( &this->thread, &this->attribute, Thread::callFunction, this );
	if (result)
	{
		cout  << endl << "Create Thread ERROR: " << (int)result; 
		return;
	}
}

// join with the thread
void Thread::join()
{
	void* status;
	pthread_attr_setdetachstate( &this->attribute, PTHREAD_CREATE_JOINABLE );
	int result = pthread_join( this->thread, &status );

	//check thread error
	if ( result != 0 )
	{
		cout << "Thread join ERROR" << endl;
		return;
	}
}

void *Thread::callFunction( void* threadId )
{
	((Thread *) threadId )->run();
	return NULL;
}

//stop the thread
void Thread::stop()
{
	pthread_attr_destroy(&this->attribute);
	pthread_exit( this );
}

